package com.lesent.kafka.spring.service.impl;

import com.lesent.kafka.spring.Constant.Constant;
import com.lesent.kafka.spring.common.JsonHelper;
import com.lesent.kafka.spring.service.IKafkaService;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.concurrent.ExecutionException;

/**
 * @author shengtao
 * @Description: kafka服务
 * @date 2018/12/19 16:22
 */
@Service
public class KafkaServiceImpl implements IKafkaService {

    @Autowired
    private KafkaTemplate<String, String> template;

    @Override
    public <T> RecordMetadata send(String topic, String key, T t) throws ExecutionException, InterruptedException {
        if (StringUtils.isEmpty(topic)) {
            topic = Constant.DEFAULT_TOPIC;
        }
        String value = JsonHelper.obj2Json(t);
        ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, key, value);
        /*this.template.send(record).addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onFailure(Throwable throwable) {

            }

            @Override
            public void onSuccess(@Nullable SendResult<String, String> stringStringSendResult) {
                stringStringSendResult.getRecordMetadata();
            }
        });*/
        SendResult<String,String> result = this.template.send(record).get();
        return result.getRecordMetadata();
    }


}
